import pyttsx3
import speech_recognition as sr
import SparkApi

# 讯飞API参数设置
appid = "5e3c0787"  # 讯飞APPID
api_secret = "Y2U5MzdhOTBmNjczNzQ1MTc3NjYyZjhi"  # 讯飞APISecret
api_key = "9311047bdf96bddd92464526bb1cf8eb"  # 讯飞APIKey

domain = "generalv3.5"  # 使用的对话领域版本
Spark_url = "wss://spark-api.xf-yun.com/v3.5/chat"  # 讯飞对话服务地址

# 初始化语音引擎
engine = pyttsx3.init()
recognizer = sr.Recognizer()


def getText(role, content):
    return {"role": role, "content": content}


def listen():
    with sr.Microphone() as source:
        recognizer.adjust_for_ambient_noise(source, duration=1)  # 适应环境噪声
        print("请说话...")
        audio = recognizer.listen(source)
        try:
            text = recognizer.recognize_google(audio, language='zh-CN')
            print(f"我: {text}")
            return text
        except sr.UnknownValueError:
            print("抱歉，我没能理解你说的话。")
            return None
        except sr.RequestError as e:
            print(f"语音识别服务不可用: {e}")
            return None


if __name__ == '__main__':
    while True:
        spoken_text = listen()
        if spoken_text:
            question = getText("user", spoken_text)

            # 获取回答
            SparkApi.answer = ""
            SparkApi.main(appid, api_key, api_secret, Spark_url, domain, [question])
            answer_text = SparkApi.answer

            # 打印回答并使用语音引擎立即播放
            # print("星火:", answer_text)
            engine.say(answer_text)
            engine.runAndWait()
